package com.syg.servlet02;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * 区分字符流和字节流的不同(字符流下载以后不能打开)
 */
@WebServlet("/diffStream")
public class _05_Different_Stream extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取文件的下载路径
        String realPath = this.getServletContext().getRealPath("/Images/许可证.png");
        //2.获取文件名
        String fileName = realPath.substring(realPath.lastIndexOf("\\")+1);
        //3.设置content-disposition响应头控制浏览器以下载的形式打开文件
        resp.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode(fileName,"utf-8"));
        //4.获取文件输入流
        FileReader in = new FileReader(realPath);
        //5.定义缓存大小
        char[] charCache = new char[1024];
        //6.获取响应输出流
        PrintWriter respOut = resp.getWriter();
        //7.将文件流写入到缓冲区
        int len = 0;
        while ((len = in.read(charCache))>0){
            respOut.write(charCache);//(输出一部分,会在浏览器显示一部分,可以断点观察)
        }
    }
}
